package com.example.tutorial.mytodolist;

import java.util.ArrayList;
import java.util.Calendar;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

import com.example.tutorial.arrayadapter.TaskArrayAdapter;
import com.example.tutorial.model.DaoMaster;
import com.example.tutorial.model.DaoMaster.DevOpenHelper;
import com.example.tutorial.model.DaoSession;
import com.example.tutorial.model.Task;
import com.example.tutorial.model.TaskDao;

public class ListTaskActity extends Activity {

	ArrayList<Task> listTask;
	ListView list;

	TaskArrayAdapter adapter;
	
	private PendingIntent pendingIntent;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_list_task);
		
		DevOpenHelper helper = new DevOpenHelper(this, "task-db", null);
		SQLiteDatabase db = helper.getWritableDatabase();
		DaoMaster daoMaster = new DaoMaster(db);
		DaoSession daoSession = daoMaster.newSession();
		TaskDao taskDao = daoSession.getTaskDao();

		listTask = new ArrayList<Task>();
		listTask.addAll(taskDao.loadAll());
		adapter = new TaskArrayAdapter(this, listTask);

		list = (ListView) findViewById(R.id.listTask);
		list.setAdapter(adapter);

		list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				try {
					// TODO Auto-generated method stub
					Task item = listTask.get(position);
					if (item != null) {
						Intent intent = new Intent(getApplicationContext(),
								AddTaskActity.class);
						intent.putExtra("TASKID", item.getId());
						
						Bundle extras = new Bundle();
				        extras.putLong("TASKID", item.getId());
				        
						startActivity(intent);
					}
				} catch (Exception e) {
					TextView title = (TextView)arg1.findViewById(R.id.title);
					title.setText("Error:" + e.getMessage());
				}
			}
		});
	}

	public void redirectAdd(View v) {
		Intent intent = new Intent(getApplicationContext(), AddTaskActity.class);
		startActivity(intent);
	}

	public void refreshTask(View v) {
		adapter.notifyDataSetChanged();
		list.setAdapter(adapter);
	}
}
